import json
import os

class Temp:
    """
    MakeCase for Auto Api test cases structures.
    print xxx.yml, test_xxx.py, xxx_api.py and create them if not exist
    """
    def __init__(self, path, payload: dict, func, method):
        self.payload = payload
        self.path = path
        self.func = func
        self.ob = self.func.split('_')[1]
        self.method = method
        if self.method == 'POST':
            self.payload_type = 'json'
        if self.method == 'GET':
            self.payload_type = 'params'
        self.data_dir = self.path.split('/')[2]
        self.result = []

    def make_dir(self, path):

        folder = os.path.exists(path)

        if not folder:  # 判断是否存在文件夹如果不存在则创建为文件夹
            os.makedirs(path)  # makedirs 创建文件时如果路径不存在会创建这个路径
            return f"{path} 创建成功。"
            # print(f"{path} 创建成功。")
        else:
            # print(f"{path} 创建失败，文件夹已存在！！！")
            return f"{path} 创建失败，文件夹已存在！！！"


    def make_file(self, filedir, filename, content):
        """
        create files or folders base on test requirements
        :param filedir:
        :param filename:
        :param content:
        :return: result: 1,自动生成参数化yml文件 2,自动生成测试用例 3,自动生成接口封装
        """
        if filename.split('.')[1] == 'yml':
            path = f"..\\data\\api\\{filedir}"
            # self.result.append('='*40+' 自动生成参数化yml文件 '+'='*40+'\n')
            self.result.append(self.make_dir(path))
            # self.make_dir(path)
        if 'test_' in filename or '_test' in filename:
            path = f"..\\api_test\\testcases\\{filedir}"
            # self.make_dir(path)
            self.result.append(self.make_dir(path))

        if '_api' in filename:
            path = f"..\\api_test\\api\\{filedir}"
            # self.make_dir(path)
            self.result.append(self.make_dir(path))

        file = f"{path}\\{filename}"
        # with open(f"..\\data\\api\\{filedir}\\{filename}", 'w', encoding='utf-8') as f:
        if not os.path.isfile(file):
            with open(file, 'w', encoding='utf-8') as f:
                f.write(content)
                self.result.append(f"{file} 创建成功\n")
        else:
            # print(f"{file} 已存在！！！")
            self.result.append(f"{file} 已存在！！！\n")
            # return f"{path} 创建失败，文件夹已存在！！！"

    def make_api(self):
        # 空字符替换为 ~
        for k, v in self.payload.items():
            if not v:
                self.payload[k] = '~'
        #
        dd_list = []
        dd_list_v = []
        dd_list_none = []
        for k, v in self.payload.items():
            dd_list.append(k)
            dd_list_v.append(v)
            dd_list_none.append(f"{k}=None")
        params = f"{', '.join(dd_list)}"
        vars_none = ', '.join(dd_list_none)
        dd_list_v_toStr = f"{', '.join([str(v) for v in dd_list_v])}"

        # 自动生成参数化yml文件
        print("")
        yml_content = f"""
{self.func}:
  # - [ids,  {params}]
  - [Required filds, {dd_list_v_toStr}, 200]
  # - [All filds, {dd_list_v_toStr}, 200]
        """
        print('='*40+' 自动生成参数化yml文件 '+'='*40+'\n', yml_content)
        self.make_file(self.ob, self.ob+'.yml', yml_content)
        # print(vars_none)

        # 自动生成测试用例
        case_content = f"""import allure
import pytest
from utils.data_loader import DataLoader


class Test{self.ob.capitalize()}:

    {self.ob}_data = DataLoader.load_case_data('api', '{self.data_dir}', '{self.ob}.yml')
    {self.func}_data = {self.ob}_data['{self.func}']
    {self.func}_ids = [d.pop(0) for d in {self.func}_data]

    @pytest.mark.parametrize('{params}, expect', {self.func}_data, ids={self.func}_ids)
    def test_{self.func}(self, {self.ob}, {params}, expect):
        with allure.step("步骤1：新增进口车"):
            {self.ob}.{self.func}({params})
        with allure.step("断言结果"):
            assert {self.ob}.jsonpath("$.code")[0] == expect
        """
        print('='*40+' 自动生成测试用例 '+'='*40+'\n', case_content)
        self.make_file(self.ob, 'test_'+self.ob+'.py', case_content)
        for k, v in self.payload.items():
            self.payload[k] = k
    # 生成接口封装代码:
        api_content = f"""from api_test.api.feishu_api import FeiShuApi
        

class {self.ob.capitalize()}Api(xxxApi):
    def __init__(self):
        super().__init__()
        self.{self.ob}_ids = []

    def {self.func}(self, {vars_none}):
        path = "{self.path}"
        payload = {json.dumps(self.payload, indent=12, ensure_ascii=False)}
        res = self.send_request("{self.method}", self.base_url + path, {self.payload_type}=payload)
        # 判断请求结果
        if res.status_code == 200:
            self.json_data = res.json()
            if self.jsonpath(expr="$.code")[0] == 200:
                self.ids += self.jsonpath("$..id")
                print(f"\\n检查结果: {{self.ids}}")
        else:
            print(res.status_code, res.text)
        """
        print('='*40+' 自动生成接口封装 '+'='*40+'\n', api_content)
        self.make_file(self.ob, self.ob+'_api.py', api_content)

        # 输出执行结果
        # print(self.result)
        for r in self.result:
            print(r)


